import * as React from 'react';
import { listStore } from '../../stores/list';
import { observer } from 'mobx-react';
import { WeaTableNew } from 'comsMobx';
import {WeaLocaleProvider,WeaTag,WeaTools,WeaCheckbox} from "ecCom";
const { viewer } = WeaTools;
const getLabel = WeaLocaleProvider.getLabel;
import jQuery from 'jquery';
import { observable, toJS} from 'mobx';
import { Dropdown,Menu,Spin,message } from 'antd';
import { isExitIconHandle } from './utils';
import { removeHTMLTag } from '../../util'
const WeaTable = WeaTableNew.WeaTable;
const MenuItem = Menu.Item;

export interface EditTableCellProps {
    datatemp?: any;
    store:listStore;
    cellIndex:any
}
@observer
class ImgCell extends React.Component<EditTableCellProps, any> {
    customOperates = (record ,index, operates) => {
        const { store } = this.props;
        const itemsArr: any = [];
        let operatesshow = record.operatesshowspan;
        let likestatus = record.likesinfospan && record.likesinfospan.split(',')[2] ? record.likesinfospan.split(',')[2] : '';
        let likecount = record.likesinfospan && record.likesinfospan.split(',')[0] ? record.likesinfospan.split(',')[0] : '0';
        let dislikecount = record.likesinfospan && record.likesinfospan.split(',')[1] ? record.likesinfospan.split(',')[1] : '0';
        const isExitIcon = isExitIconHandle('customOpt', operates, operatesshow);
        operates.map(function (value, index1, array) {
            if (operatesshow.split('+')[index1] && operatesshow.split('+')[index1] == 'true') {
                if (array[index1].nodeName && array[index1].nodeName == 'operate') {
                    if (array[index1].href == 'javascript:likes') {
                        let classname = 'icon-coms02-like-o';
                        let titlename = array[index1].text;
                        let key = '1';
                        if (likestatus == '1') {
                            classname = 'icon-coms02-like';
                            titlename = getLabel('31129', '取消') + array[index1].text;
                            key = '0';
                        }
                        itemsArr.push(<MenuItem>
                            <a
                                href="javascript:void(0);"
                                onClick={() => {
                                    store.likeOrDislike(record, key,index,'0');
                                }}
                            >
                                <i title={titlename} className={classname}/>
                                {' ' + array[index1].text + ' (' + likecount + ')'}
                            </a>
                        </MenuItem>);
                    } else if (array[index1].href == 'javascript:dislikes') {
                        let classname = 'icon-coms02-Negative-comment-o';
                        let titlename = array[index1].text;
                        let key = '2';
                        if (likestatus == '2') {
                            classname = 'icon-coms02-Negative-comment';
                            titlename = getLabel('31129', '取消') + array[index1].text;
                            key = '0';
                        }
                        itemsArr.push(<MenuItem>
                            <a
                                href="javascript:void(0);"
                                onClick={() => {
                                    store.likeOrDislike(record, key,index,'0');
                                }}
                            >
                                <i title={titlename} className={classname}/>
                                {' ' + array[index1].text + ' (' + dislikecount + ')'}
                            </a>
                        </MenuItem>);
                    } else {
                        itemsArr.push(<MenuItem>
                            <a
                                href="javascript:void(0);"
                                onClick={() => {
                                    store.doCustomButton(record, '', array[index1], '');
                                }}
                            >
                                {isExitIcon ? <div className='cube-list-icon-box'>{array[index1].icon?<img src={array[index1].icon}/>:''}</div>:''}
                                {array[index1].text}
                            </a>
                        </MenuItem>);
                    }
                }
            }
        })
        return (
            <Menu>
                {itemsArr}
            </Menu>
        );
    };
    
    render() {
        const { datatemp,store,cellIndex } = this.props;
        const { titleField,dataShowInfo,userInfo,checkBtn,doRealAction,selectRowkeys} = store;
        let titleShowname = "";
        let titleDecu = "";
        let orherTitle = "";
        let orherTitleDecu : any ="";
        let orherTitleDecuArr :any = [] ;
        let imgFieldSecu = "";
        let selectRowkey ="";
        if(datatemp){
            datatemp.randomFieldId ? datatemp.randomFieldSubKeyd_id != undefined ? selectRowkey = datatemp.randomFieldId + "_" + datatemp.randomFieldSubKeyd_id : selectRowkey = datatemp.randomFieldId : "";
            let index = 0;
            store.newTable.columns.map((item) => {
                if(item.hasOwnProperty('display') && item.display == 'true'){
                    const fieldkey = item.dbField;
                    const fieldkeyspan = fieldkey && fieldkey+"span";
                    let params = item.transMethodOther;
                    let fielddbtype = params && params.split("+")[2];
                    let fieldtype = params && params.split("+")[3];
                    if(fieldkey && titleField && titleField.fieldname && fieldkey == titleField.fieldname && item.display!="none"){
                        titleDecu = datatemp[fieldkeyspan];
                    }
                    if(fieldkey && dataShowInfo && dataShowInfo.datashowtypefilefieldname && fieldkey == dataShowInfo.datashowtypefilefieldname){
                        if(datatemp[fieldkeyspan] && datatemp[fieldkeyspan].indexOf("empty-columns") < 0 && datatemp[fieldkeyspan].split("|||")[0]){
                            imgFieldSecu = datatemp[fieldkeyspan].split("|||")[0] + "&f_weaver_belongto_userid="+userInfo.userid+"&f_weaver_belongto_usertype="+userInfo.usertype;
                        }else if(dataShowInfo.datashowtypefileicon){
                            imgFieldSecu ="/weaver/weaver.file.FileDownload?fileid=" + dataShowInfo.datashowtypefileicon;
                        }
                    }
                    if(index < 4 && fieldkey && (!titleField || (titleField && titleField.fieldname && fieldkey != titleField.fieldname)) && (!dataShowInfo || ( dataShowInfo.datashowtypefilefieldname && fieldkey != dataShowInfo.datashowtypefilefieldname)) && fieldkey != 'randomFieldId' && fieldkey.indexOf('expandid_')<0 && item.display!="none"){
                        titleShowname = item.title;
                        if (item.dataIndex == 'modelableid') {//如果是标签
                            const keyspanArr = datatemp[fieldkeyspan]?JSON.parse(datatemp[fieldkeyspan]):[];
                            orherTitleDecu = keyspanArr.map(tag => {
                                if (tag.tabname != '') {
                                    orherTitle += tag.tabname+",";
                                    return <WeaTag title={tag.tabname} style={{
                                        borderRadius: '4px',
                                        marginBottom: 2,
                                        marginRight: 10,
                                        color: tag.color,
                                        backgroundColor: tag.bgcolor,
                                        borderColor: tag.bdcolor
                                    }}>
                                        {tag.tabname.length > 10 ? `${tag.tabname.slice(0, 10)}...` : tag.tabname}
                                    </WeaTag>
                                } else {
                                    return tag.tabname + " ";
                                }
                            });
                        }else{
                            orherTitleDecu = datatemp[fieldkeyspan];
                            if(orherTitleDecu.indexOf("|||")>=0){
                                var arr = orherTitleDecu.split("|||");
                                orherTitle = arr[0];
                                orherTitleDecu = arr[1];
                            }else{
                                orherTitle = removeHTMLTag(orherTitleDecu);
                            }
                            if(fielddbtype == "1" && fieldtype == "1"){
                                orherTitle =  datatemp[fieldkey];
                            }
                        }
                        let customDom:any = this.renderCheck(item,fieldkeyspan);
                        if(item.dataIndex !== "isshowlist" && (!((fielddbtype == "2") || (fielddbtype == "6" && fieldtype == "2") || fielddbtype == "7"))){//html格式多文本、图片
                            orherTitleDecuArr.push(
                                <div className="td-otherCol">
                                    {
                                        item.dataIndex == 'modelableid' ? <div className='td-otherCol-decu' title = {orherTitle}>{orherTitleDecu}</div>
                                        :  <React.Fragment>
                                                <div title = {titleShowname}>{titleShowname}:</div>
                                                {
                                                    customDom ? customDom : this.addSpan(orherTitleDecu,'',orherTitle)
                                                }
                                            </React.Fragment> 
                                    }
                                </div>
                            )
                            index = index + 1;
                        }
                        orherTitleDecu="";
                        titleShowname="";
                        orherTitle = "";
                    }
                }
            });
            let opt:any = this.renderCustomBtn();
            let tdStyle = `imgType-tdCol-innerHtml ${selectRowkeys.indexOf(selectRowkey)>-1 ? 'tdCol-select' : 'tdCol-noselect'}`;
            const isFilterData = doRealAction && checkBtn && datatemp[checkBtn] == 'true' ? true : false;// 数据筛选
            isFilterData ? tdStyle += ' tdCol-filter' : '';
            return (
                <td className={tdStyle}>
                    <div id={'imgtpyetdDiv'+cellIndex} onClick={this.onClickImgCell.bind(this,isFilterData)}> 

                        <div className='cubeImgtd-img' onClick={this.stopClick}>                                    
                            { imgFieldSecu ?  <img data-imgsrc={imgFieldSecu} src={imgFieldSecu} className='formImgPlay' onClick={(e)=>{viewer(e);}}/> : '' }
                        </div>

                        <div className="cubeImgtd-title">
                            {this.addSpan(titleDecu)}
                            {opt && <div className={"imgType-td-opt"} onClick={this.stopClick}>{opt}</div>}
                        </div>

                        <div className="cubeImgtd-info">                               
                            {orherTitleDecuArr}
                            {selectRowkey && <div id={'imgtpyeselectCol'+ cellIndex} className="td-selectCol">{selectRowkey}</div>}
                            <div className="cubeImgtd-selectInfo">
                                <div><i className={isFilterData ? 'icon-mode-close' : 'icon-coms-Selected'} /></div>
                            </div>
                        </div>
                    </div>
                </td>
            );
        }
    }

    addSpan = (htmlVal,classNameVal?,title?) =>{
        if(htmlVal.indexOf("</a>")>-1){
            htmlVal = htmlVal.replace(/<br\s*>|<br\s*\/>/g,'');
        }
        let isNeedSpan = htmlVal.indexOf('cube-list-progress') < 0;
        let domParams = {
            className:classNameVal,
            title:title
        }
        return (
            <div {...domParams}>
                <span className={`td-otherCol-content-${isNeedSpan ? 'span' : 'nospan'}`} onClick={this.stopClick} dangerouslySetInnerHTML={{ __html:htmlVal }}></span>
            </div>
        )
    }

    onClickImgCell = (isFilterData) => {
        const { store,cellIndex } = this.props;
        if(!isFilterData){
            store.selectRowKey(cellIndex)
        }else{
            message.info(getLabel('521170','数据不可勾选'))
        }
    }

    stopClick = (e) => {
        e.stopPropagation()
    }

    // 前端处理check框
    renderCheck = (item,fieldkeyspan) => {
        const { datatemp } = this.props;
        if(item.className && item.className.indexOf("checkBox") > 0){
            let valueSpan = datatemp[fieldkeyspan];
            if (valueSpan != '0' && valueSpan != '1' && valueSpan != '') {//被转换 去除条件record[newColumn.dataIndex]!=''&&，当check框为空时也显示转换
                return <span title={valueSpan} dangerouslySetInnerHTML={{ __html: valueSpan }}></span>;
            } else {
                return <div style={{ whiteSpace: 'normal' }}>
                    <WeaCheckbox
                        viewAttr='1'
                        id={valueSpan}
                        value={valueSpan}>
                    </WeaCheckbox>
                </div>
            }
        }
        return 
    }

    // 自定义按钮
    renderCustomBtn = () => {
        const { store,datatemp,cellIndex } = this.props;
        const operater = store.newTable.operates;
        if(toJS(operater).length>0){
            const menu = this.customOperates(datatemp, cellIndex, operater)
            return (
                <Dropdown overlay={menu}>
                    <i className="icon-coms-more"></i>
                </Dropdown>
            )
        }
        return
    }

}

export interface ImgSearchProps {
    store: listStore;
}

@observer
export default class ImgSearch extends React.Component<ImgSearchProps>{
    @observable height = 0;
    @observable selectRowkeys : string[] = [];
    
    componentWillMount(){
        const { store } = this.props;
        store.getListInfoForImgSearch(store.customId);
    }

    componentDidUpdate() {
        const { store } = this.props;
        const {newTable} = store;
        const pagesize = newTable.pageSize;
        let timeCounter: any;
        timeCounter = setTimeout(() => {
            clearTimeout(timeCounter);
            try {
                const paginationHeight = jQuery('.ant-pagination.ant-table-pagination').height() + 32 || 46;
                const headerHeight = jQuery('.ant-table-header').height() || 40;
                let mxheight =jQuery('.wea-new-top-content').height() - jQuery('#btnDiv').height() - jQuery('.cube-list-countContainer').height() - headerHeight - paginationHeight - 50;
                if(store.isShowCondition){
                    mxheight = mxheight - jQuery('.wea-search-container').height();
                }
                mxheight && jQuery('.imgTypeDiv-tableCol-innerHtml').css('maxHeight', mxheight);
            } catch (e) {
            }
        }, 100);

        for(var t=0;t<pagesize;t++){
            const tempvalue = jQuery(`#imgtpyeselectCol${t}`) && jQuery(`#imgtpyeselectCol${t}`).text();
            if(store.selectRowkeys.indexOf(tempvalue)>-1){
                jQuery(`#imgtpyetdDiv${t}`).parent().attr('class','imgType-tdCol-innerHtml tdCol-select')
            }
        }
    }

    render() {
        const { store } = this.props;
        const { newTable } = store;
        const total = newTable.count;
        let styleStr = 'ant-table-placeholder';
        return (
            <Spin spining={store.searchImg.loading}>
                {
                    total && total > 0 ?
                        ( !store.searchImg.loading ? this.getImgSearchTable()
                            :  <div className={styleStr}></div>
                        )
                        : <div className={styleStr}>
                            <i className="anticon anticon-frown" style={{marginRight:4}} />
                            {getLabel(83553, '暂无数据')}
                        </div>
                }
            </Spin>
        )
    }

    getImgSearchTable = () => {
        const { store } = this.props;
        if(store.newTable){
            return(
                <div id='imgSearchTable' className="imgTypeDiv-tableCol-innerHtml" style={{overflow:'scroll'}}>
                    <table cellSpacing="35" className="imgType-tableCol-innerHtml">
                        {this.getImgSearchTr()}
                    </table>
                </div>
            )
        }else{
            return(
                <WeaTable
                    className="cube-list-table"
                    register_table={store.register_table}
                    comsWeaTableStore={store.newTable}
                    needScroll={true}
                    heightSpace={10}
                    pagination={false}
                    tableWidth={store.originalTableWidth}
                    hasOrder={true}
                    onOperatesClick={store.doCustomButton}
                    expiredRefreshFun={store.refresh}
                />
            )
        }
    }

    getImgSearchTr = () => {
        const {store} = this.props;
        const {newTable} = store;
        const { count,current,pageSize } = newTable;
        const rownum = (count-current*pageSize)>=0?Math.ceil(pageSize/5):Math.ceil((count-(current-1)*pageSize)/5);//行数，一行展示5个图片
        let otherFieldMap : any = [] ; 
        for(var i = 0; i < rownum;i++){
            otherFieldMap.push(
                <tr className="imgType-tdCol-innerHtml">
                    {this.getImgSearchTd(i)}
                </tr>
            );
        }
        return otherFieldMap;
    }
    
    getImgSearchTd = (rownum : any) => {
        const { store } = this.props;
        const { newTable } = store;
        const { count,current,pageSize } = newTable
        let pagesize = 5;
        if(pageSize<5) pagesize = pageSize;
        let maxcolnum = (count-current*pageSize)>=0?pagesize*(rownum+1):(current-1)*pageSize+5*(rownum+1)>count?count-(current-1)*pageSize+5*rownum:pagesize*(rownum+1);
        let otherFieldMap : any = [] ;
        if(maxcolnum > 0){
            for(let t =5*rownum; t < maxcolnum; t++){
                let datatemp = store.newTable.datas.length > t ?store.newTable.datas.get(t):"";
                if(datatemp){
                    otherFieldMap.push(
                        <ImgCell datatemp={datatemp} store={store} cellIndex={t}></ImgCell>
                    )
                }
            }
            if(maxcolnum < 5){
                for(var index = maxcolnum; index < 5; index++){
                    otherFieldMap.push(
                        <td></td>
                    );
                }
            }
        }else{
            otherFieldMap.push(
                <td></td>
            );
        }
        return otherFieldMap;
    }
}